package com.xxkk.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author xxkk
 * @version 1.0.0
 * @title XKHttpUtil
 * @description ʕ•ᴥ•ʔ
 * @create 2025/1/16 18:08
 **/
public class XKHttpUtil {

    public static void main(String[] args) throws IOException {
        String urlString = "https://graph.facebook.com/v21.0/1106248570978214/events?access_token=EAAOqgVK3a98BOwZCP6UZAnKs8vooys07ZBfn7OJAsIu8mEPcJPk0N8Ni5V7AS11xWbmkkZB2zJJlvskH9DiPjVUbzxt1sKluYISPtWPcjtTuCdkAe8mh7LxZC0cUKZBVJcVTJKNMeJwrnc8rOrSdgxxj813SCeF7VIbsXwP4B5yEYKT7BCjfVXNAaxBWqWMjdjAAZDZD";
        String jsonData = "{\n" +
                "    \"data\": [\n" +
                "        {\n" +
                "            \"event_name\": \"CompleteRegistration\",\n" +
                "            \"event_time\": 1737017878,\n" +
                "            \"user_data\": {\n" +
                "                \"em\": [\n" +
                "                    \"309a0a5c3e211326ae75ca18196d301a9bdbd1a882a4d2569511033da23f0abd\"\n" +
                "                ],\n" +
                "                \"ph\": [\n" +
                "                    \"254aa248acb47dd654ca3ea53f48c2c26d641d23d7e2e93a1ec56258df7674c4\",\n" +
                "                    \"6f4fcb9deaeadc8f9746ae76d97ce1239e98b404efe5da3ee0b7149740f89ad6\"\n" +
                "                ],\n" +
                "                \"client_ip_address\": \"123.123.123.123\",\n" +
                "                \"client_user_agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0\",\n" +
                "                \"fbc\": \"fb.1.1554763741205.AbCdEfGhIjKlMnOpQrStUvWxYz1234567890\",\n" +
                "                \"fbp\": \"fb.1.1558571054389.1098115397\"\n" +
                "            },\n" +
                "            \"action_source\": \"website\"\n" +
                "        }\n" +
                "    ],\n" +
                "    \"test_event_code\": \"TEST35898\"\n" +
                "}";
        XKHttpUtil.sendPostRequest(urlString, jsonData);
    }

    /**
     * @param urlString
     * @param jsonData
     * @return
     * @throws IOException
     */
    public static String sendPostRequest(String urlString, String jsonData) throws IOException {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setDoOutput(true);

        try (OutputStream os = conn.getOutputStream()) {
            byte[] input = jsonData.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);// 发送JSON数据
        }

        int responseCode = conn.getResponseCode();// 获取响应代码
        if (responseCode != HttpURLConnection.HTTP_OK) {
            System.out.println("Request was failed.");
            System.out.println("Response Code: " + responseCode);
        }
        // 接收响应数据
        StringBuilder response = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
            String responseLine;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }
        }
        return response.toString();
    }

    public static String sendPostRequest(String urlString, Map<String, String> urlParams, Map<String, Object> jsonData) throws IOException {
            // 构建URL带参数
            StringBuilder urlWithParams = new StringBuilder(urlString);
            if (!urlParams.isEmpty()) {
                urlWithParams.append("?");
                for (Map.Entry<String, String> entry : urlParams.entrySet()) {
                    urlWithParams.append(entry.getKey());
                    urlWithParams.append("=");
                    urlWithParams.append(entry.getValue());
                    urlWithParams.append("&");
                }
                urlWithParams.deleteCharAt(urlWithParams.length() - 1); // 删除最后一个 "&"
            }
            String  url = urlWithParams.toString();

            // 将Map转换为JSON字符串
            StringBuilder jsonString = new StringBuilder("{");
            for (Map.Entry<String, Object> entry : jsonData.entrySet()) {
                jsonString.append("\"")
                        .append(entry.getKey())
                        .append("\":")
                        .append(entry.getValue())
                        .append(",");
            }
            jsonString.deleteCharAt(jsonString.length() - 1); // 删除最后一个逗号
            jsonString.append("}");
        return sendPostRequest(urlString,jsonString.toString());
    }
}
